import { createStore } from 'vuex'
import { shopCarListItem, tablistItemType } from '@/interface'

export default createStore<any>({
  state: {
    shopCarList: []
  },
  mutations: {
    // 添加购物车
    CHANGE_SHOP_CAR_LIST(state, payload:tablistItemType) {
      if(state.shopCarList.some((item:shopCarListItem) => item.id === payload.id)) {
        state.shopCarList = state.shopCarList.map((item:shopCarListItem) => {
          if(item.id === payload.id) {
            return {
              ...item,
              num: item.num + 1
            }
          } else return item
        })
      } else {
        state.shopCarList.unshift({...payload, num: 1})
      }
    },
    FILTER_SHOP_LIST(state, payload) {
      const { num, id } = payload;
      // 更改数量
      state.shopCarList = state.shopCarList.map((item:shopCarListItem) => {
        if(item.id === id) {
          return {
            ...item,
            num: item.num + num
          }
        } else return item
      })

      // 过滤数据
      state.shopCarList = state.shopCarList.filter((item:shopCarListItem) => item.num)
    }
  },
  actions: {
  },
  modules: {
  }
})
